package cn.zdm.authserver.config.authentication;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * copyright (C), 2021, 北京同创永益科技发展有限公司
 *
 * @author ZhaoDeman
 * @version 1.0.0
 * <author>                <time>                  <version>                   <description>
 * ZhaoDeman        2021/1/6 14:13                 1.0                        登录失败的处理Handler
 * @program auth-server
 * @description 登录失败的处理Handler
 * @create 2021/1/6 14:13
 */
@Slf4j
public class SecurityAuthenticationFailureHandler extends ExceptionMappingAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.info("登录失败====>{}", "登录失败");
        if (request.getHeader("accept").contains("application/json")) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            PrintWriter out = response.getWriter();
            // 输出失败的原因
            out.write("{\"error_code\":\"401\", \"name\":\"" + e.getClass() + "\", \"message\":\"" + e.getMessage() + "\"}");
        } else {
            super.onAuthenticationFailure(request, response, e);
        }
    }
}
